package handle

import (
	"context"
	"gitee.com/crack007/goose/core"
	"gitee.com/crack007/goose/core/web"
	"gitee.com/crack007/goose/injection"
	"github.com/crack007/go-im/src/common/config"
	"github.com/crack007/go-im/src/common/monitor"
	"github.com/crack007/go-im/src/module/api/middleware"
	"github.com/crack007/go-im/src/module/api/router"
	"github.com/crack007/go-im/src/module/api/service"
)

type apiHandle struct {
	web.DefaultHttpServerHandle
}

func NewApiHandle() *apiHandle {
	return &apiHandle{}
}
func (h *apiHandle) OnInitInject() []injection.Service {
	return []injection.Service{injection.MYSQL_SERVICE, injection.REDIS_SERVICE}
}
func (h *apiHandle) OnInitConfig() {
	config.InitAppConfig()
}

func (h *apiHandle) OnInitRouter() {
	webServer := h.GetHttpServer()
	webServer.Engine.Use(middleware.CORSMiddleware(), middleware.PrometheusMiddleware)
	router.ApiV1(webServer)
}

func (h *apiHandle) OnInitService() {
	service.RegisterApiService(h.GetHttpServer().Ctx)
	h.GetHttpServer().AddGracefulTask(core.NewGracefulTask(func(ctx context.Context) {
		service.ApiService.Bootstrap(ctx)
	}))

	service.MessageService.GracefulExit(h.GetHttpServer().Ctx)
	h.GetHttpServer().AddGracefulTask(core.NewGracefulTask(func(ctx context.Context) {
		service.MessageService.Consume()
	}))
	go func() {
		middleware.RegisterPrometheus()
		monitor.NewPrometheus()
	}()
}
